package cn.tsmchina.one.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.tsmchina.one.domain.user.Customer;
import cn.tsmchina.one.service.user.CustomerService;

public class CustomerInterceptor implements HandlerInterceptor {
	@Autowired
	private CustomerService customerService;
	
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,
		Object handler) throws Exception {
		String path = request.getServletPath();
		//登录：要放行
		if(path.startsWith("/login") || path.startsWith("/kaptcha") 
				|| path.startsWith("/fileUpload") || path.startsWith("/msg")
				|| path.startsWith("/logout") || path.startsWith("/ciderr.html")){
			return true;
		}
		
		boolean suc = true;
		String loginIdStr = request.getParameter("cid");//这里的cid其实是loginId
		long loginId = -1;
		long customerId = -1;
		if(loginIdStr==null || (loginIdStr!=null && loginIdStr.trim().isEmpty())) {
			Customer customer = (Customer) request.getSession().getAttribute("historyCustomer");
			if(customer==null) {
				customer = (Customer) request.getSession().getAttribute("customer");
				if(customer==null) {
					suc = false;
				} else {
					loginId=customer.getLoginId();
					customerId=customer.getId();
				}
			} else {
				loginId=customer.getLoginId();
				customerId=customer.getId();
			}
		} else {
			try {
				loginId = Long.parseLong(loginIdStr.toString());
			} catch (Exception e) {
				suc = false;//wrong cid
			}
			
			Customer newCustomer = customerService.getCustomerByLoginId((int)loginId);
			if(newCustomer==null) {
				suc = false;//invalid cid
			} else {
				//replace customer
				Customer customer = (Customer) request.getSession().getAttribute("historyCustomer");
				if(customer==null) {
					request.getSession().setAttribute("historyCustomer", newCustomer);
				} else {
					if(customer.getId()!=newCustomer.getId()) {
						request.getSession().setAttribute("historyCustomer", newCustomer);
					}
				}
				loginId = newCustomer.getLoginId();
				customerId=newCustomer.getId();
			}
		}
		if(!suc)
			response.sendRedirect(request.getContextPath()+"/ciderr.html");
		else {
			request.setAttribute("customerId", customerId);
			request.setAttribute("loginId", loginId);
		}
		return suc;
	}  
	
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}